package com.wl.index.login.controller;

import com.wl.bean.Result;
import com.wl.biz.BizException;
import com.wl.index.login.biz.ILvuserBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpSession;
import com.wl.util.Utils;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/lvuser")
public class lvuserController {
    @Autowired
    ILvuserBiz lvuserBiz;

    JdbcTemplate jdbcTemplate;

    @RequestMapping("login")
    public String login(String uname, String password, HttpSession session) throws BizException {
        Utils.checkEmpty(uname,"清输入账号");
        Utils.checkEmpty(password,"请输入密码");
        Utils.check(password.trim().length() < 3,"密码至少是三个字符");

        String sql = "select * from lvuser where uname=? and password=?";
        sql = String.format(sql,uname,password);
        List list = jdbcTemplate.queryForList(sql);

        Utils.check(list.isEmpty(),"账号或密码错误");
        Utils.check(list.size() > 1, "数据库设计问题");
        Object lvuser = list.get(0);

        session.setAttribute("lvuser",lvuser);

        Map<String,Object> map = new HashMap<>();
        map.put("lvuser",lvuser);

        Object aGoto = session.getAttribute("goto");
        if (aGoto == null) {
            map.put("goto",aGoto);
            session.removeAttribute("goto");
        }
        return new Result(1,"登录成功",map).toString();
    }

    @RequestMapping("myinfo")
    Result myinfo(HttpSession session) throws BizException {
        Object myinfo = session.getAttribute("myinfo");
        if (myinfo == null) {
            throw new BizException("未登录");
        }
        return new Result(1,"已登录",myinfo);
    }

    @RequestMapping("logout")
    ModelAndView logout(ModelAndView modelAndView, HttpSession session){
        session.invalidate();
        modelAndView.setViewName("redirect:/");
        return modelAndView;
    }
}
